/**
 * 微信渠道路由管理器
 * 1、接收微信消息
 * 2、获取微信用户基本信息
 * 3、回复微信消息
 */
var _ljs=require("../mmlog").root("[sever/channel/weixin.js]");

var wechat = require("wechat"),
	util = require("../util"),
	_channel = require("../channelManager"),
	_api=require("./WeChat-API");

var config=null;

module.exports = {

	init: function(app, express,_configSelf) {
		
		config=_configSelf;
		util.init(_configSelf);
		
		app.use(express.query());
		app.use("/wechat", wechat(config.wechat("config"),
			wechat.text(function(message, req, res, next) {
				res.reply();
				_channel.message(config.vars.wechat, message);
				_ljs.info("微信文本消息\n", message);
				next();
			}).event(function(message, req, res, next) {
				res.reply('正在接入人工客服、请稍等...');
				_channel.session(config.vars.wechat, message,function(val){
					_api.reply(message.FromUserName,{
						type:"text",
						content:val
					})
				});
				_ljs.info("微信菜单事件消息\n", message);
				next();
			}).image(function(message, req, res, next) {
				_ljs.info("微信图片消息\n", message);
				_channel.message(config.vars.wechat, message);
				res.reply();
			}).voice(function(message, req, res, next) {
				_ljs.info("微信语音消息\n", message);
				_channel.message(config.vars.wechat, message);
				res.reply();
			}).video(function(message, req, res, next) {
				_ljs.info("微信视频消息\n", message);
				res.reply();
			})
		));
		app.use("/wc/test", function(req, res, next) {
			var r = _channel.session(config.vars.wechat, req.body);
			_ljs.debug("微信菜单事件消息", req.body);
			if (r == true) {
				res.json({
					code: "正在进入人工"
				})
			} else {
				res.json({
					code: "已经在人工了"
				});
			}
		})
		app.use("/wc/message", function(req, res, next) {
			_ljs.debug("微信消息", req.body);
			var r = _channel.message(config.vars.wechat, req.body);
			res.json({
				code: "0"
			});
		})
	}
}